<template>

  <el-container>
    <el-header>
      <!-- 查询条件 -->
      <el-row>
        <div class="block">

          <!-- <el-space :size="size" spacer="|"> -->

          <el-button type="success" @click="ShowPatList">患者列表</el-button>
          <!-- <el-button  type="success" @click="canDO=true" width="120px" :disabled="canDO">月份</el-button> -->

          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>

          <el-input v-model="nameOrBed" style="width: 240px" placeholder="姓名或床号" :prefix-icon="Search" />
          <!-- 
          <el-text class="mx-1">名字</el-text>
          <el-input v-model="input" style="width: 100px" placeholder="Please input" />

          <el-text class="mx-1">床号</el-text>
          <el-input v-model="input" style="width: 240px" placeholder="Please input" /> -->
          <el-button type="primary" @click="RtmsSearchHandle">查询</el-button>
          <span>
            <el-button icon="Plus" type="success" @click="ShowRtmsDiag" :disabled="canDO">添加记录</el-button>
            <el-button :icon="Printer" type="warning" @click="handlePrint" :disabled="canDO">统计</el-button>
          </span>
          <!-- </el-space> -->
        </div>
      </el-row>
    </el-header>
    <el-main>
      <div class="home">

        <!-- 数据列表 -->
        <el-row :gutter="20">
          <el-col :span="24">

            <el-table :data="RtmsList" ref="multipleTable" style="width: 100%; " :height="tableHeight" stripe
              :summary-method="getSummaries" show-summary table-layout="auto">

              <!-- 添加行号列 -->
              <el-table-column type="index" label="行号" width="60">
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="RECORD_TIME" :formatter="dateFormatter" label="记录时间" width="120">
              </el-table-column>
              <el-table-column prop="NAME" label="姓名" min-width="80"> </el-table-column>
              <el-table-column prop="BED" label="床号" min-width="80"> </el-table-column>
              <el-table-column prop="PART" label="部位" min-width="80"> </el-table-column>
              <el-table-column prop="SPORT" label="运动阈值" min-width="80"> </el-table-column>
              <el-table-column prop="HZ" label="频率" min-width="80"> </el-table-column>
              <el-table-column prop="DURATION" label="刺激时长" min-width="80"> </el-table-column>
              <el-table-column prop="INTERVAL" label="间隔时间" min-width="80"> </el-table-column>
              <el-table-column prop="SEQUENCE" label="序列数" min-width="80"> </el-table-column>
              <el-table-column prop="SIGNNAME" label="治疗师" min-width="80"> </el-table-column>

              <el-table-column align="center">
                <template #header>
                  <div class="headstr">
                    操作
                  </div>
                </template>
                <template #default="scope">
                  <el-button type="primary" size="small" @click="RtmsEditHandle(scope.$index, scope.row)">
                    修改
                  </el-button>
                  <el-button type="danger" size="small" @click="RtmsDelHandle(scope.$index, scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-col>
        </el-row>

      </div>
    </el-main>
  </el-container>

  <!-- 左侧患者列表-->
  <el-drawer title="患者信息" v-model="drawerVis" direction="ltr">
    <div>
      <el-row>
        <button @click="Addhandle">添加</button>
      </el-row>
      <el-table :data="PatList" style="width: 100%;" stripe>
        <el-table-column prop="NAME" label="姓名" width="80"> </el-table-column>
        <el-table-column prop="SEX" label="性别" width="80"> </el-table-column>
        <el-table-column prop="AGE" label="年龄" width="80"> </el-table-column>
        <el-table-column prop="BED" label="床号" width="80"> </el-table-column>
        <el-table-column prop="INTIME" :formatter="dateFormatter" label="入院时间" width="120">
        </el-table-column>
        <el-table-column align="right" fixed="right" width="80">
          <template #header>
            <div class="headstr">
              操作
            </div>
          </template>
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-drawer>

  <!-- 新增患者对话框 -->
  <el-dialog v-model="dialogFormVisible" width="400px" title="患者信息">
    <el-form :model="AddModel" label-width="100px" label-position="right">
      <el-form-item label="姓名:">
        <el-input v-model="AddModel.NAME" />
      </el-form-item>
      <el-form-item label="性别:">
        <el-select v-model="AddModel.SEX" placeholder="选择性别">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
          <el-option label="空" value="" />
        </el-select>

      </el-form-item>
      <el-form-item label="年龄:">
        <el-input-number v-model="AddModel.AGE" :min="0" />
        <!-- <el-input v-model="AddModel.AGE" /> -->
      </el-form-item>
      <el-form-item label="床号:">
        <el-input v-model="AddModel.BED" />
      </el-form-item>
      <el-form-item label="入院日期:">
        <el-date-picker v-model="AddModel.INTIME" type="date" placeholder="入院日期" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveHandle">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 新增rtms -->
  <el-dialog v-model="rtmsDiagVisible" width="800px" title="经颅磁记录信息">

    <el-form :model="RtmsModel" label-width="100px" label-position="right">
      <el-form-item label="记录日期:">
        <el-date-picker v-model="RtmsModel.RECORD_TIME" type="date" placeholder="记录时间" />
      </el-form-item>
      <el-form-item label="患者:">
        <div style="text-align: center">
          <el-transfer v-model="ChooseTrans" filterable :titles="['全部患者', '选中患者']" :filter-method="filterMethod"
            filter-placeholder="输入名字" :data="TransList" />
        </div>
      </el-form-item>

      <el-form-item label="运动阀值:">
        <el-input v-model="RtmsModel.SPORT" />
      </el-form-item>
      <el-form-item label="频率:">

        <el-select v-model="RtmsModel.HZ" placeholder="选择频率">
          <el-option label="1Hz" value="1Hz" />
          <el-option label="2Hz" value="2Hz" />
          <el-option label="" value="" />
        </el-select>

      </el-form-item>
      <el-form-item label="刺激时长:">
        <el-input-number v-model="RtmsModel.AGE" :min="0" />
        <!-- <el-input v-model="AddModel.AGE" /> -->
      </el-form-item>
      <el-form-item label="间隔时间:">
        <el-input v-model="RtmsModel.DURATION" />
      </el-form-item>
      <el-form-item label="序列数:">
        <el-input v-model="RtmsModel.SEQUENCE" />
      </el-form-item>
      <el-form-item label="治疗师:">
        <el-input v-model="RtmsModel.SIGNNAME" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="rtmsDiagVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveRtmsHandle">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from "dayjs";
import { reactive, toRefs, ref, getCurrentInstance, watch, onMounted, toRaw, watchEffect } from "vue";

//组件
import { ElNotification } from "element-plus"
//Api
//import { QueryPatientInHospital, SavePatientInHospital, QueryRtmsRecord, SaveRtmsRecords, DelRtmsRecord } from "../util/request"
import NurseAPI from "@/api/nurse";
//----查询条件

const drawerVis = ref(false)

//显示rtms 录入
function ShowRtmsDiag() {
  rtmsDiagVisible.value = true;

}

function ShowPatList() {

  console.log(1111);
  drawerVis.value = true;
}
// 选择月份
const chooseDate = ref('')

//可操作记录
const canDO = ref(false)

//新建弹出框显示隐藏
const dialogFormVisible = ref(false)
//新建按钮
function Addhandle() {
  let now = new Date();
  let data = {
    "ID": 0,
    "SID": "0",
    "NAME": "",
    "BED": "",
    "AGE": 56,
    "SEX": "",
    "INTIME": "2024-12-04 12:00:00",
    "ISOUT": 0,
    "PATIENTID": "",
    "OUTTIME": null
  }
  AddModel.value = data;
  dialogFormVisible.value = true;
}
//提示成功
const showSuccess = () => {
  ElNotification({
    title: '成功',
    message: '操作成功',
    type: 'success',
  })
}
//提示失败
const showFail = (msg) => {
  ElNotification({
    title: '失败',
    message: msg,
    type: 'error',
  })
}
//修改按钮
function handleEdit(i, b) {
  // 取出原始对象
  const m = toRaw(b);
  console.log(m.SID);
  var parm = { id: m.SID };
  NurseAPI.GetNurseDayWorkById(parm).then((res) => {
    console.log(res.data.data);
    if (res.data.code == 200) {

      console.log("查询单条");
      AddModel.value = res.data.data;
      //弹出添加界面
      dialogFormVisible.value = true;
    } else {
      showFail(res.data.msg);
    }
  });
}

//添加实体
const AddModel = ref({});
//患者列表
const PatList = ref([]);

//穿梭框数据源

const TransList = ref([]);

//选中的穿梭框数据
const ChooseTrans = ref([]);

//过滤穿梭框
const filterMethod = (query, item) => {

  return item.label.toLowerCase().includes(query.toLowerCase())
}

//------------------------------rtms-----------

//rtms弹出框是否展示
const rtmsDiagVisible = ref(false);
//添加的实体
const RtmsModel = ref({});

//rems记录数据
const RtmsList = ref([]);

const startDay = dayjs().startOf('day');
const endDay = dayjs().endOf('day');
//时间段
const dateRange = ref([startDay, endDay]); // 默认赋值
//名字和床号
const nameOrBed = ref("");

//经颅磁恢复默认
function RtmsDefault() {
  rtmsDiagVisible.value = false;
  let now = dayjs().format('YYYY-MM-DD HH:mm:ss')
  RtmsModel.value = {
    "ID": 0,
    "SID": "0",
    "NAME": "",
    "PATIENTID": "",
    "BED": "",
    "AGE": 0,
    "SEX": "",
    "RECORD_TIME": now,
    "PART": "",
    "SPORT": "30%",
    "STRONG": "30%",
    "HZ": "1Hz",
    "DURATION": "10min",
    "INTERVAL": "1s",
    "SEQUENCE": "",
    "SIGNNAME": ""
  }
}

//搜索rtms记录
function RtmsSearchHandle() {
  RtmsDefault();
  let parm = { StartTime: '', EndTime: '', SearchTest: '' };
  parm.StartTime = dateRange.value[0];
  parm.EndTime = dateRange.value[1];
  parm.SearchTest = nameOrBed.value;
  console.log(parm)
  NurseAPI.QueryRtmsRecord(parm).then((res) => {
    RtmsList.value = res;
  });
}

//保存一条经颅磁记录
function SaveRtmsHandle() {
  let chooseArr = ChooseTrans.value;
  if (chooseArr.length == 0) {
    showFail('请至少选择一名患者！');
    return;
  }
  let pats = chooseArr.map(index => PatList.value[index - 1])
  console.log(pats)
  let parm = [];
  let tyMoel = RtmsModel.value;
  for (let index = 0; index < pats.length; index++) {
    let pat1 = pats[index];
    let pat2 = { ...tyMoel };
    pat2.NAME = pat1.NAME;
    pat2.BED = pat1.BED;
    parm.push(pat2);
  }
  console.log(parm)
  NurseAPI.SaveRtmsRecords(parm).then((res) => {
    RtmsList.value = res.data.data;
    RtmsSearchHandle();
  }).catch((msg) => {
    showFail(msg);
  });
}


function RtmsEditHandle() {


}
//删除
function RtmsDelHandle(i, b) {

  ElMessageBox.confirm(
    '确定要删除这条经颅磁记录吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const parm = toRaw(b);

    NurseAPI.DelRtmsRecord(parm).then((res) => {
      console.log(res.data)
      RtmsList.value = res;
      RtmsSearchHandle();
    }).catch(() => {
      showFail(res.data.msg);
    });

  })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}


//----------------------------
//查询患者
function SearchHandle() {
  let parm = {};
  NurseAPI.QueryPatientInHospital(parm).then((res) => {
    PatList.value = res;
    let trans = [];
    res.forEach(function (c) {
      trans.push({ key: c.ID, label: c.BED + " - " + c.NAME, disabled: false });
    });
    TransList.value = trans;
  }).catch((msg) => {
    showFail(msg);
  });
}

//保存
function SaveHandle() {
  const pdata = toRaw(AddModel.value);

  console.log(pdata);
  NurseAPI.SavePatientInHospital(pdata).then((res) => {

    if (res.data.code == 200) {
      showSuccess();
      dialogFormVisible.value = false;
      SearchHandle();
    }
    else {
      showFail(res.data.msg);
    }
  });
}


//显示总共多少条
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  sums[0] = '记录总数:'
  if (data && data.length)
    sums[1] = `共计${data.length}条`
  return sums
}
const tableHeight = ref('');
const getTableHeight = () => {
  let tableH = 120; //距离页面下方的高度
  let tableHeightDetil = window.innerHeight - tableH;
  if (tableHeightDetil <= 300) {
    tableHeight.value = 300;
  } else {
    tableHeight.value = window.innerHeight - tableH;
  }
};

function dateFormatter(row, column) {

  let datetime = row.RECORD_TIME;
  if (datetime) {
    datetime = new Date(datetime);
    let y = datetime.getFullYear() + '-';
    let mon = datetime.getMonth() + 1 + '-';
    let d = datetime.getDate();
    return y + mon + d;
  }
  return ''
}

watchEffect(() => {
  getTableHeight();
});

//挂载完毕
onMounted(() => {

  //当天日期
  let dtStr = dayjs().format('YYYY-MM');
  let df = dayjs(dtStr);
  chooseDate.value = df;
  RtmsSearchHandle();
  SearchHandle();
  RtmsDefault();
})

</script>

<style scoped lang="scss">
.pageheader {
  display: flex;
  flex-direction: row;
  justify-items: flex-start;
  vertical-align: middle;
  align-items: center;
}

.bottomGroup {
  position: fixed;
  z-index: 999;
  bottom: 0px;
  left: 0px;
  width: 100%;
  overflow: hidden;
  background-color: grey;
  color: white;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  height: 60px;
  padding: 20px;
  margin: 0px 2px;
  box-sizing: border-box;
}

.footer-area {
  height: 10px;
}

.box-card {
  padding: 0px;
  margin: 0px;
}

.headstr {
  text-align: center;
}
</style>